package com.hiwan.system.dao.sequence;

import java.util.HashMap;
import java.util.Map;

import org.framework.dao.ServiceUtilDao;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional(propagation = Propagation.REQUIRES_NEW)
public class SeqDao extends ServiceUtilDao {
	public synchronized int getAndIncreaseSeq(String key, String area, String date) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("key", key);
		map.put("area", area);
		map.put("date", date);
		
		Integer seq = selectOne("selectSeq", map, Integer.class);
		if (seq == null) {
			insert("insertSeq", map);
			return 0;
		} else {
			update("updateSeq", map);
			return seq + 1;
		}
	}
	public synchronized String selectSeq(String key, String area) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("key", key);
		map.put("area", area);
		String update_date = selectOne("selectUpdateDate", map, String.class);
		return update_date;
	}
	public synchronized int deleteSeq(String key, String area) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("key", key);
		map.put("area", area);
		int  result = delete("deleteSeq", map);
		return result;
	}
	public synchronized int getAndIncreaseSeq(String key, String area) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("key", key);
		map.put("area", area);
		map.put("date", "*");

		Integer seq = selectOne("selectSeq", map, Integer.class);
		if (seq == null) {
			insert("insertSeq", map);
			return 0;
		} else {
			update("updateSeq", map);
			return seq + 1;
		}
	}

	public synchronized int getAndIncreaseSeq(String key) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("key", key);
		map.put("area", "*");
		map.put("date", "*");

		Integer seq = selectOne("selectSeq", map, Integer.class);
		if (seq == null) {
			insert("insertSeq", map);
			return 0;
		} else {
			update("updateSeq", map);
			return seq + 1;
		}
	}

	public int getLock(String area, String lockKey) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("lockKey", lockKey);
		map.put("area", area);
		Integer status = selectOne("selectLockStatus", map, Integer.class);

		if (status == null) {
			status = 0;
		}
		return status;
	}

	public int setLock(String area, String lockKey, int lockStauts) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("lockKey", lockKey);
		map.put("area", area);
		map.put("lockStauts", lockStauts);

		return update("updateLockStatus", map);
	}
}
